package com.manage.server.service.impl;

import com.manage.server.service.FileStorageService;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
public class FileStorageServiceImpl implements FileStorageService {
    // 使用跨平台路径

//    private static final String avatarPath = "D:/study/code/idea/ideaProject/SysManage/server/src/main/resources/com/manage/static/avatars";
    private static final String avatarPath = "server/src/main/resources/com/manage/static/avatars/";

    @Override
    public String storeAvatar(MultipartFile file, Integer userId) throws IOException {
        Path uploadPath = Paths.get(avatarPath).toAbsolutePath().normalize();

        // 创建目录（如果不存在）
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = "avatar_" + userId + "_" + System.currentTimeMillis() + fileExtension;

        // 保存文件
        Path destination = uploadPath.resolve(newFilename);
        Files.copy(file.getInputStream(), destination, StandardCopyOption.REPLACE_EXISTING);

        return newFilename;
    }

    @Override
    public Resource loadAvatar(String filename) {
        try {
            Path file = Paths.get(avatarPath).resolve(filename).normalize();
            Resource resource = new UrlResource(file.toUri());

            if (resource.exists() && resource.isReadable()) {
                return resource;
            } else {
                throw new RuntimeException("文件不存在或不可读: " + filename);
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException("文件路径错误: " + filename, e);
        }
    }
}